/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2013
 */


package com.smg.community.controller;


import static com.smg.community.util.ProjectUtil.getLoginNameType;
import static com.smg.community.util.ProjectUtil.getRegTargetType;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javacommon.base.BaseRestSpringController;
import javacommon.util.FileUtil;
import javacommon.util.HtmlToText;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.org.rapid_framework.page.Page;

import com.google.gson.Gson;
import com.smg.community.model.SmgGroup;
import com.smg.community.model.SmgKeyword;
import com.smg.community.model.SmgMember;
import com.smg.community.model.SmgMemberBehavior;
import com.smg.community.model.SmgMemberFocus;
import com.smg.community.model.SmgMemberPointDetail;
import com.smg.community.model.SmgMemberVisit;
import com.smg.community.model.SmgTopic;
import com.smg.community.service.HttpRequestProxy;
import com.smg.community.service.SmgMemberPointDetailManager;
import com.smg.community.util.Constant;
import com.smg.community.util.DateFormatUtil;
import com.smg.community.util.GsonUtil;
import com.smg.community.util.ImageCutUtil;
import com.smg.community.util.ProjectUtil;
import com.smg.community.util.StringUtil;
import com.smg.community.vo.query.SmgGroupQuery;
import com.smg.community.vo.query.SmgTopicQuery;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/member")
public class SmgMemberController extends BaseRestSpringController<SmgMember,java.lang.Long>{
	private static Properties p ;
	
	

	public static String accountId  ;
	
	public static String pwd  ;

	
	public static String REG_LOGIN_SEVICE_URL;
	
	public static final String recvEncoding = "UTF-8";
	
	
	static {
		 p = FileUtil.loadProperties("config.properties");
		 pwd = p.getProperty("pwd");
		 accountId = p.getProperty("accountId");
		 REG_LOGIN_SEVICE_URL = p.getProperty("REG_LOGIN_SEVICE_URL");
	}
	/**
	 * 
	 */
	Log logger = LogFactory.getLog(SmgMemberController.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static String hideMobileNumber(String mobileNumber){
		  String pre  = mobileNumber.substring(0,4);
		  String end = mobileNumber.substring(7,mobileNumber.length());
		  return pre +"****"+end;
	  }
	  public static String hideEmail(String email){
		  int index = email.indexOf("@");
		  String pre  = email.substring(0,1);
		  String end = email.substring(index,email.length());
		  return pre +"****"+end;
	  }

	/**
	 * 登录接口只通过接口登录
	 * @return
	 */
	@RequestMapping(value="/ajaxlogin")
	public @ResponseBody Map<String,Object> login(HttpServletRequest request){
		String password = request.getParameter("password");
		String loginName = request.getParameter("loginName");
		String md5Password = StringUtil.getMD5Str(password);
		Map<String,Object> map = new HashMap<String,Object>();
		//如果本地库没有此用户  尝试从接口登录
		int type = getLoginNameType(loginName) ;
	
		String loginUrl = REG_LOGIN_SEVICE_URL +"/account/login.action";
		//?params={username="+loginName+"&passwd="+password;
		//2:手机号
		//3:邮箱
		try {
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("username", loginName);
			paramMap.put("type", type+"");
			paramMap.put("passwd", password);
			Gson gson = new Gson();
			String param = gson.toJson(paramMap);
			loginUrl = loginUrl +"?param="+param;
			logger.debug(loginUrl);
			String loginResult = HttpRequestProxy.doGet(loginUrl, recvEncoding);
			if ( loginResult == null){
				map.put("state",Constant.NULL_RESULT_STATE);
				map.put("desc",Constant.NULL_RESULT_STATE_DESC);
			}else{
				Map<String,String> loginResultMap = GsonUtil.getMapByJsonString(loginResult);
				if ( loginResultMap.get("resultCode").equals(Constant.SUCCESS_RESULT_CODE)){
					//登录成功的话插入本地用户表
					SmgMember member = new SmgMember();
					member.setAppSource("pc");
					member.setAppVersion("1.0.0");
					if ( type ==  Constant.REG_TAGRT_EMAIL ) {
						member.setEmail(loginName);
						member.setIsEmailVerify(1);
						member.setIsMobileVerify(0);
					}else if ( type == Constant.REG_TAGRT_MOBILE){
						member.setMobileNumber(loginName);
						member.setIsMobileVerify(1);
						member.setIsEmailVerify(0);
					}
					member.setHeadImage(null);
					member.setLastLoginDate(new Date());
					member.setLoginName(loginName);
					String nickName = loginResultMap.get("nickName");
			        if ( nickName == null || nickName.equals("")){
			        	//2:手机号
			    		//3:邮箱
			        	if ( type == 2){
			        		try{
			        			nickName = hideMobileNumber(loginName);
			        		}catch(Exception e){
			        			e.printStackTrace();
			        		}
			        	}else if ( type == 3 ){
			        		try{
			        			nickName = hideEmail(loginName);
			        		}catch(Exception e){
			        			e.printStackTrace();
			        		}
			        	}
			        }
					member.setNickName(nickName);
					member.setPassword( StringUtil.getMD5Str(password));
					member.setRegDate(new Date());
					member.setRegSource("pc");
					member.setSex("m");
					member.setSignature("");
					member.setThirdPartyToken(null);
					member.setTopicCount(0);
					member.setIsNewMember(0);
					try {
						SmgMember tmp =  null;
						if ( type > 1 ){
							tmp = smgMemberManager.getByLoginName(loginName);
						}else {
							tmp = smgMemberManager.getByNickname(loginName);
						}
						if ( tmp  == null ){
							smgMemberManager.save(member);
						}else{
							member = tmp;
							member.setNickName(loginResultMap.get("nickName").equals("")?loginName:loginResultMap.get("nickName"));
						}
						// 
						request.getSession().setAttribute("token",loginResultMap.get("nickName").equals("")?loginName:loginResultMap.get("nickName"));
						//将社区的密码和这里的密码统一
						smgMemberManager.updatePassword(member.getMemberId(), md5Password);
						smgMemberManager.updateNickname(member.getMemberId(),loginResultMap.get("nickName"));
						smgMemberManager.updateNicknameFirstchar(member.getMemberId(), cn2FirstSpell(loginResultMap.get("nickName")));
						member.setPassword(md5Password);
						saveMemberInSession(request,member);
					}catch(Exception e){
						e.printStackTrace();
					}
					map.put("member", member);
					map.put("state",Constant.SUCCESS_STATE);
					map.put("desc",loginResultMap.get("resultMsg"));
					
					return map;
				}else{
					map.put("state",Constant.ERROR_STATE);
					map.put("desc",loginResultMap.get("resultMsg"));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("state",Constant.RUNTIME_EXPCETIION_STATE);
			map.put("desc",Constant.RUNTIME_EXPCETIION_STATE_DESC);
			return map;
		}
		//不从本地登录,否则数据全乱了
		/**
		try {
			SmgMember member = smgMemberManager.getByLoginNameAndPassword(loginName,md5Password);
			if ( member != null){
				map.put("member", member);
				map.put("state",Constant.SUCCESS_STATE);
				saveMemberInSession(request,member);
				return map;
			}else{
				map.put("state",Constant.ERROR_STATE);
				map.put("desc","登录失败,用户名或者密码错误.");
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("state",Constant.RUNTIME_EXPCETIION_STATE);
			map.put("desc",Constant.RUNTIME_EXPCETIION_STATE_DESC);
			return map;
		}**/
		return map;
	}
	/**
	 * 注册需要调用两个接口
	 * 1. getverifycode 获取验证码
	 * 2. reg           将用户信息和验证码一起提交完成注册
	 * 
	 * @param nickName    用户昵称
	 * @param loginName   登录名 手机号码或者邮箱
	 * @param password    密码
	 * @return
	 */
	@RequestMapping(value="/getverifycode")
	public @ResponseBody Map<String,Object> getVerifyCode(@RequestParam String  nickName,@RequestParam String  loginName,@RequestParam String  password){
		Map<String,Object> map = new HashMap<String,Object>();
		//type*	int	1手机号 2邮箱
		int type = getRegTargetType(loginName);
		try{
			logger.debug( (  type == Constant.INVALID_LOGINNAME   ));
			if ( type == Constant.INVALID_LOGINNAME){
				map.put("state",Constant.INVALID_LOGINNAME_STATE);
				map.put("desc",Constant.INVALID_LOGINNAME_STATE_DESC);
				return map;
			}
			String preRegUrl = REG_LOGIN_SEVICE_URL+"/account/register.action";
			Map<String,Object> paramMap = new HashMap<String,Object>(); 
			paramMap.put("type",type);
			paramMap.put("passwd",password);
			paramMap.put("nickName",nickName);
			paramMap.put("target",loginName);
			Gson gson = new Gson();
			String param = gson.toJson(paramMap);
			preRegUrl = preRegUrl +"?param="+param;
			logger.debug(preRegUrl);
			String  result = HttpRequestProxy.doGet(preRegUrl,recvEncoding);
			if ( result == null){
				map.put("state",Constant.NULL_RESULT_STATE);
				map.put("desc",Constant.NULL_RESULT_STATE_DESC);
			}else{
				Map<String,String> preRegMap = GsonUtil.getMapByJsonString(result);
				if ( preRegMap.get("resultCode").equals(Constant.SUCCESS_RESULT_CODE)){
					map.put("state",Constant.SUCCESS_STATE);
					map.put("desc",Constant.SUCCESS_STATE_DESC);
				}else{
					map.put("state",Constant.ERROR_STATE);
					map.put("desc",preRegMap.get("resultMsg"));
				}
				
			}
			return map;
		}catch(Exception e){
			e.printStackTrace();
			map.put("state",Constant.RUNTIME_EXPCETIION_STATE);
			map.put("desc",Constant.RUNTIME_EXPCETIION_STATE_DESC);
			return map;
		}
	}
	/**
	 * 注册需要调用两个接口
	 * 1. getverifycode 获取验证码
	 * 2. reg           将用户信息和验证码一起提交完成注册
	 * 
	 * @param nickName    用户昵称
	 * @param loginName   登录名 手机号码或者邮箱
	 * @param password    密码
	 * @return
	 */
	@RequestMapping(value="/findpassword")
	public @ResponseBody Map<String,Object> findPassword(@RequestParam String loginName){
		String preRegUrl = REG_LOGIN_SEVICE_URL+"/account/findPwd.action";
		Map<String,Object> paramMap = new HashMap<String,Object>();
		int type = getRegTargetType(loginName);
		paramMap.put("type",type);
		paramMap.put("target",loginName);
		Gson gson = new Gson();
		String param = gson.toJson(paramMap);
		preRegUrl = preRegUrl +"?param="+param;
		logger.debug(preRegUrl);
		String  result = HttpRequestProxy.doGet(preRegUrl,recvEncoding);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("state",Constant.SUCCESS_STATE);
		map.put("desc",result);
		return map;
	}
	/**
	 * @return
	 */
	@RequestMapping(value="/logout")
	public  @ResponseBody Map<String,Object>  logout(HttpServletRequest request,ModelMap model){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("state",Constant.SUCCESS_STATE);
		map.put("desc","success");
		clearMemberInSession(request);
		return map;
	}
	/**
	 * @return
	 */
	@RequestMapping(value="/reg/success")
	public String regSuccess(HttpServletRequest request,ModelMap model){
		SmgMember loginMember = getLoginMember(request);
		if ( loginMember == null){
			return toErrorPage(model, "您未登录哦~");
		}
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		return "/member/regSuccess"; 
	}
	/**
	 * @return
	 */
	@RequestMapping(value="/login")
	public String login(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		return "/member/intologin"; 
	}
	/**
	 * @return
	 */
	@RequestMapping(value="/login/success")
	public String loginSuccess(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember loginMember = getLoginMember(request);
		if ( loginMember == null){
			return toErrorPage(model, "您没有登录哦～");
		}
		model.addAttribute("loginMember",loginMember);
		Calendar c = Calendar.getInstance();
		
		int hour = c.get(Calendar.HOUR_OF_DAY);
		String msg = "";
		//凌晨登录
		if ( hour>=23 ||  hour <=6){
			msg = "你我都是夜猫子";
		}else if( hour >6 && hour <=12){
			msg = "早上好";
		}else if( hour >12 && hour <=18){
			msg = "下午好";
		}else if( hour >18 && hour <=20){
			msg = "晚上好";
		}else if( hour >20 && hour <=23){
			msg = "夜深了,注意休息";
		}
		model.addAttribute("msg",msg);
		return "/member/loginsuccess"; 
	}
	
	/**
	 * @return
	 */
	@RequestMapping(value="/reg")
	public String intoReg(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		return "/member/intoreg";
	}
	
	
	
	
	/**
	 * @param nickName   昵称
	 * @param loginName  登录名 手机或者邮箱
	 * @param password   密码
	 * @param verifyCode 验证码
	 * @param appSource  app的来源  I 或者 A 
	 * @param appVersion app版本
	 * @param regSource  注册来源 手机或者pc
	 * @return
	 */
	@RequestMapping(value="/regaction")
	public @ResponseBody Map<String,Object> reg(@RequestParam String  nickName,@RequestParam String  loginName,@RequestParam String  password
			,@RequestParam String verifyCode
			,HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,String> paramMap = new HashMap<String,String>();
		int type = getRegTargetType(loginName);
		if ( type == Constant.INVALID_LOGINNAME){
			map.put("state",Constant.INVALID_LOGINNAME_STATE);
			map.put("desc",Constant.INVALID_LOGINNAME_STATE_DESC);
		}
		paramMap.put("target",loginName);
		paramMap.put("type",getRegTargetType(loginName)+"");
		paramMap.put("verCode",verifyCode);
		Gson gson = new Gson();
		String param = gson.toJson(paramMap);
		String addMemberUrl = REG_LOGIN_SEVICE_URL+"/account/addAccount.action?param="+param;
		logger.debug(addMemberUrl);
		String addMemberResult =  HttpRequestProxy.doGet(addMemberUrl, recvEncoding);
		if ( addMemberResult == null ){
			map.put("state",Constant.NULL_RESULT_STATE);
			map.put("desc",Constant.NULL_RESULT_STATE_DESC);
		}else{
			Map<String,String> addMemberMap = GsonUtil.getMapByJsonString(addMemberResult);
			if ( addMemberMap.get("resultCode").equals(Constant.SUCCESS_RESULT_CODE)){
				//注册成功 插入 smg_member表
				SmgMember member = new SmgMember();
				member.setAppSource("pc");
				member.setAppVersion("1.0.0");
				if ( type ==  Constant.REG_TAGRT_EMAIL ) {
					member.setEmail(loginName);
					member.setIsEmailVerify(1);
					member.setIsMobileVerify(0);
				}else if ( type == Constant.REG_TAGRT_MOBILE){
					member.setMobileNumber(loginName);
					member.setIsMobileVerify(1);
					member.setIsEmailVerify(0);
				}
				member.setHeadImage(null);
				member.setLastLoginDate(new Date());
				member.setLoginName(loginName);
				member.setNickName(nickName);
				member.setPassword( StringUtil.getMD5Str(password));
				member.setRegDate(new Date());
				member.setRegSource("pc");
				member.setSex("m");
				member.setSignature("");
				member.setThirdPartyToken(null);
				member.setTopicCount(0);
				member.setIsNewMember(1);
				member.setNickNameFirstChar(cn2FirstSpell(nickName));
				try {
					smgMemberManager.save(member);
				}catch(Exception e){
					e.printStackTrace();
				}
				map.put("member", member);
				map.put("state",Constant.SUCCESS_STATE);
				map.put("desc",Constant.SUCCESS_STATE_DESC);
				saveMemberInSession(request, member);
				
			}else{
				map.put("state",Constant.ERROR_STATE);
				map.put("desc",addMemberMap.get("resultMsg"));
			}
		}
		return map;
	}
	/**
	 * @param mobilenumber
	 * @param message
	 * @return
	 */
	@RequestMapping(value="/sendsms")
	public  @ResponseBody Map<String,Object> sendSms(@RequestParam String  mobilenumber,@RequestParam String  message){
		//由系统管理员分配的用户名+密码+时间戳，MD5加密后的字符串，加密后的字符传全部大写
		String timestamp = DateFormatUtil.getDateStr("yyyyMMddHHmmss");
		String newpwd = StringUtil.getMD5Str(pwd+timestamp);
		logger.debug(newpwd);
		newpwd = newpwd.toUpperCase();
		logger.debug(newpwd);
		try {
		//	message = URLDecoder.decode(message,"UTF-8");
			message = URLEncoder.encode(message, "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String r = HttpRequestProxy.doPost("http://221.181.73.88/sms/SmsSendInstance.do?accountId="+accountId+"&pwd="+newpwd+"&mobs="+mobilenumber+"&msg="+message+"&timestamp="+timestamp, new  HashMap<String,String>(), "utf-8");
		logger.debug(r);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("result",r);
		return resultMap;
	}
	
	public static void main(String[] arg) throws UnsupportedEncodingException{
		System.out.println(URLEncoder.encode("测试", "utf-8"));
		System.out.println("15800579445");
		System.out.println("18721616270");
	}
	/**
	 * 用户主页
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="")
	public String memberIndexDefault(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember member = getLoginMember(request);
		if ( member == null ){
			return toErrorPage(model, "您未登录或者登录已超时");
		}
		int memberId = member.getMemberId();
		return   otherMemberIndex(request,model,memberId,"",0,1);
	}
	@RequestMapping(value="/{memberId}")
	public String memberIndex(HttpServletRequest request,ModelMap model,@PathVariable int memberId){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		return   otherMemberIndex(request,model,memberId,"",0,1);
	}
	@RequestMapping(value="/{memberId}/{type}-{filter}-{pageNumber}")
	public String otherMemberIndex(HttpServletRequest request,ModelMap model,@PathVariable int memberId,@PathVariable String type,@PathVariable int filter,@PathVariable int pageNumber){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember loginMember = getLoginMember(request);
		SmgMember viewMember = smgMemberManager.getById(memberId);
		if ( viewMember == null ){
			return toErrorPage(model, "你所查看的用户不存在！");
		}
		model.addAttribute("isSelf",false);
		model.addAttribute("type",type);
		model.addAttribute("filter",filter);
		model.addAttribute("pageNumber",pageNumber);
		
		if ( loginMember != null ){
				int loginMemberId  = loginMember.getMemberId();
				int viewMemberId  = viewMember.getMemberId();
				if ( loginMemberId == viewMemberId ){
					model.addAttribute("isSelf",true);
				}else{
					smgMemberManager.addVisitCount(viewMemberId);
					SmgMemberVisit smgMemberVisit = new SmgMemberVisit();
					smgMemberVisit.setFromMemberHeadImage(loginMember.getHeadImage());
					smgMemberVisit.setFromMemberId(loginMember.getMemberId());
					smgMemberVisit.setFromMemberName(loginMember.getNickName());
					smgMemberVisit.setToMemberHeadImage(viewMember.getHeadImage());
					smgMemberVisit.setToMemberId(viewMember.getMemberId());
					smgMemberVisit.setToMemberName(viewMember.getNickName());
					smgMemberVisit.setVisitDate(new Date());
					smgMemberVisitManager.save(smgMemberVisit);
					//判断是否能关注
					SmgMemberFocus s =smgMemberFocusManager.getByMemberIdAndFocuseId(loginMember.getMemberId(), viewMember.getMemberId());
					if ( s!=null){
						viewMember.setFocusDate(s.getFocusDate());
					}
				}
		}
		model.addAttribute("viewMember",viewMember);
		if ( type.equals("")){
			SmgTopicQuery topicQuery = new SmgTopicQuery();
			topicQuery.setPageNumber(1);
			topicQuery.setTopicType(1);
			topicQuery.setPageSize(6);
			topicQuery.setOrderBy("createdate desc");
			setStartAndLimit(topicQuery, 1,6);
			topicQuery.setFkCreateMemberId(viewMember.getMemberId());
			List<SmgTopic> topicList = smgTopicManager.getByQuery(topicQuery);
			for(SmgTopic topic:topicList) {
				ProjectUtil.filterTopic(topic);
			}
			model.addAttribute("topicList",topicList);
		
			
			topicQuery.setPageNumber(1);
			topicQuery.setTopicType(2);
			topicQuery.setPageSize(2);
			topicQuery.setFkCreateMemberId(viewMember.getMemberId());
			List<SmgTopic> activityList = smgTopicManager.getByQuery(topicQuery);
			for(SmgTopic topic:activityList) {
				ProjectUtil.filterTopic(topic);
			}
			model.addAttribute("activityList",activityList);
			
			List<SmgGroup> joinGroupList = smgGroupManager.getByMemberId(viewMember.getMemberId(),7);
			model.addAttribute("joinGroupList",joinGroupList);
			List<SmgMemberBehavior> behaviorList = smgMemberBehaviorManager.getMemberBehaviorListByMemberId(viewMember.getMemberId(),8);
			model.addAttribute("behaviorList",behaviorList);
			List<SmgMember> focusMemberList = smgMemberManager.getFocusMemberByMemberId(viewMember.getMemberId(),9);
			model.addAttribute("focusMemberList",focusMemberList);
			return "/member/index";
		}else if ( type.equals("activity")){
			SmgTopicQuery query = new SmgTopicQuery();
			query.setPageNumber(pageNumber);
			query.setTopicType(2);
			setStartAndLimit(query, pageNumber,15);
			query.setOrderBy("createdate desc");
			//创建的
			if ( filter == 1) {
				query.setFkCreateMemberId(viewMember.getMemberId());
				Page<SmgTopic> topicPage  = smgTopicManager.findActivityPage(query);
				int count = 0 ;
				String description = "";
				for(SmgTopic topic:topicPage) {
					if ( count == 0 ){
						String planText = HtmlToText.getPlainText(topic.getTopicContAfterFilter());
						if (planText.length() > 100){
							planText = planText.substring(0,100);
						}
						description = viewMember.getNickName()+"的最新活动: "+topic.getTopicTitleAfterFilter()+" : "+ planText;
					}
					count ++;
					
					ProjectUtil.filterTopic(topic);
				}
				model.addAttribute("description",description);
				model.addAttribute("topicPage",topicPage);
				//参加的
			}else if (filter == 2){
				query.setJoinMemberId(viewMember.getMemberId());
				Page<SmgTopic> topicPage  =  smgTopicManager.findMemberJioinActivityPage(query);		
				int count = 0 ;
				String description = "";
				for(SmgTopic topic:topicPage) {
					if ( count == 0 ){
						String planText = HtmlToText.getPlainText(topic.getTopicContAfterFilter());
						if (planText.length() > 100){
							planText = planText.substring(0,100);
						}
						description = viewMember.getNickName()+"的最新活动: "+topic.getTopicTitleAfterFilter()+" : "+ planText;
					}
					count ++;
					
					ProjectUtil.filterTopic(topic);
				}
				model.addAttribute("description",description);
				model.addAttribute("topicPage",topicPage);
			}
			return "/member/activity";
		}else if ( type.equals("group")){
			SmgGroupQuery query = new SmgGroupQuery();
			query.setStart(0);
			query.setLimit(25);
			//创建的
			if ( filter == 1){
				query.setFkMemberId(viewMember.getMemberId());
				Page<SmgGroup> groupPage = smgGroupManager.findPage(query);
				model.addAttribute("groupPage",groupPage);
				//参加的
			}else if ( filter == 2){
				query.setJoinMemberId(viewMember.getMemberId());
				Page<SmgGroup> groupPage = smgGroupManager.findMemberJoinPage(query);
				model.addAttribute("groupPage",groupPage);
			}
			return "/member/group";
		}else if ( type.equals("topic")){
			SmgTopicQuery query = new SmgTopicQuery();
			query.setPageNumber(pageNumber);
			query.setTopicType(1);
			setStartAndLimit(query, pageNumber,15);
			query.setOrderBy("createdate desc");
			//创建的
			if ( filter == 1) {
				query.setFkCreateMemberId(viewMember.getMemberId());
				Page<SmgTopic> topicPage  = smgTopicManager.findPage(query);
				String description = "";
				int count = 0;
				for(SmgTopic topic:topicPage) {
					if ( count == 0 ){
						String planText = HtmlToText.getPlainText(topic.getTopicContAfterFilter());
						if (planText.length() > 100){
							planText = planText.substring(0,100);
						}
						description = viewMember.getNickName()+"的最新帖子: "+topic.getTopicTitleAfterFilter()+" : "+ planText;
					}
					count ++;
					
					ProjectUtil.filterTopic(topic);
				}
				model.addAttribute("description",description);
				model.addAttribute("topicPage",topicPage);
				//参加的
			}else if (filter == 2){
				query.setJoinMemberId(viewMember.getMemberId());
				Page<SmgTopic> topicPage  =  smgTopicManager.findMemberReplyTopicPage(query);	
				int count = 0 ;
				String description = "";
				for(SmgTopic topic:topicPage) {
					if ( count == 0 ){
						String planText = HtmlToText.getPlainText(topic.getTopicContAfterFilter());
						if (planText.length() > 100){
							planText = planText.substring(0,100);
						}
						description = viewMember.getNickName()+"的最新帖子: "+topic.getTopicTitleAfterFilter()+" : "+ planText;
					}
					count ++;
					
					ProjectUtil.filterTopic(topic);
				}
				model.addAttribute("description",description);
				model.addAttribute("topicPage",topicPage);
			}
			return "/member/topic";
		}
		return toErrorPage(model,"访问的页面不存在");		
	}
	@RequestMapping(value="/memberInfo")
	public String memberInfo(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember viewMember = getLoginMember(request);
		if ( viewMember == null){
			return toErrorPage(model, "您未登录或者登录已超时");
		}
		model.addAttribute("viewMember",viewMember);
		model.addAttribute("type","info");
		List<Integer> yearList = new ArrayList<Integer>();
		for ( int index = 1;index <20 ;index ++){
			int year = 1970;
			year = year + index;
			yearList.add(year);
		}
		
		List<Integer> monthList = new ArrayList<Integer>();
		for ( int index = 1;index <13 ;index ++){
			monthList.add(index);
		}
		
		List<Integer> dayList = new ArrayList<Integer>();
		for ( int index = 1;index <32 ;index ++){
			dayList.add(index);
		}
		model.addAttribute("dayList",dayList);
		model.addAttribute("yearList",yearList);
		model.addAttribute("monthList",monthList);
		return "/member/memberInfo";
	}
	@RequestMapping(value="/memberinfoaction")
	public @ResponseBody Map<String,Object> memberInfoAction(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		setHeadTabIndex(model, 6);
		Map<String,Object> map = new HashMap<String,Object>();
		SmgMember viewMember = getLoginMember(request);
		try {
		setCommunityCommonModel(request, model);
	
		if ( viewMember == null){
			map.put("state","-1");
			map.put("desc","您未登录或者登录已超时");
			return   map ;
		}
		String nickName = request.getParameter("nickName");
		if ( nickName.equals(viewMember.getNickName())){
			
		}else{
			SmgMember member = smgMemberManager.getByNickname(nickName);
			if (member !=null){
				map.put("state","-1");
				map.put("desc","昵称已存在,换一个吧");
				return map;
			}
		}
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("nickName",nickName);
		paramMap.put("token",(String)request.getSession().getAttribute("token"));
		Gson gson = new Gson();
		String param = gson.toJson(paramMap);
		String editMemberPasswordUrl = REG_LOGIN_SEVICE_URL+"/account/editMember.action?param="+param;
		logger.debug(editMemberPasswordUrl);
		String editMemberPasswordResult =  HttpRequestProxy.doGet(editMemberPasswordUrl, recvEncoding);
		if ( editMemberPasswordResult == null ){
			map.put("state","-1");
			map.put("desc","修改失败,请重新登录后进行修改.");
			return map;
		}else{
				map.put("state","1");
		}
		String signature = request.getParameter("signature");
		List<SmgKeyword> keywordList = smgKeywordManager.getKeywordList();
		signature = StringUtil.filterKeyword(signature, keywordList).get("cont");
		viewMember.setNickName( StringUtil.filterKeyword(nickName, keywordList).get("cont"));
		viewMember.setNickNameFirstChar(cn2FirstSpell(viewMember.getNickName()));
		viewMember.setSignature(signature);
		String sex = request.getParameter("sex");
		viewMember.setSex(sex);
		viewMember.setBirthDay(Integer.parseInt(request.getParameter("birthDay")));
		viewMember.setBirthMonth(Integer.parseInt(request.getParameter("birthMonth")));
		viewMember.setBirthYear(Integer.parseInt(request.getParameter("birthYear")));
		smgMemberManager.update(viewMember);
		map.put("desc","更新成功");
		SmgMemberPointDetail d = smgMemberPointDetailManager.getByMemberIdAndType(viewMember.getMemberId(),60);
		if ( d == null){
			smgMemberManager.addPoint(60, 60, "完善资料获得60正能量", viewMember, request);
			map.put("desc","更新成功,获得60正能量");
		}
		}catch(Exception e){
			e.printStackTrace();
			map.put("state","-99");
			map.put("desc","崩溃..");
		}
		saveMemberInSession(request, smgMemberManager.getById(viewMember.getMemberId()));
		return map;
		
		
	}
	@RequestMapping(value="/changeHead")
	public String changeHead(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember viewMember = getLoginMember(request);
		if ( viewMember == null){
			return toErrorPage(model, "您未登录或者登录已超时");
		}
		model.addAttribute("viewMember",viewMember);
		model.addAttribute("type","head");
			return "/member/changeHead";
		}
	@RequestMapping(value="/changeHeadAction")
	public @ResponseBody String changeHeadAction(HttpServletRequest request,ModelMap model){
		SmgMember viewMember = getLoginMember(request);
		if ( viewMember == null){
			return toErrorPage(model, "您未登录或者登录已超时");
		}
		// 上传用户头像
		SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = simpleFormat.format(new Date());
		// 自定义头像
		String headNamePath  =    request.getParameter("headNamePath");
		// 如果 headNamePath 为 null 则为默认头像
//			headNamePath = ("/ddmap-web-user/images/M1/poto200.jpg".equals(headNamePath)) ? uploadPath + "images/M1/poto200.jpg" : headNamePath;
		if (null != headNamePath && "" != headNamePath) {
			// 为新剪切的头像重新命名
			String srcImgName = headNamePath.substring(headNamePath.lastIndexOf("/") + 1);
			String cutImgName = getRoundStr() + srcImgName.substring(srcImgName.lastIndexOf("."));
			String str = request.getParameter("imageProperty");
			System.out.println("剪裁大小！============"+str);    
			String[] imageProperty = str.split(",");
			ImageCutUtil iu = new ImageCutUtil(
					Integer.parseInt(imageProperty[0]),
					Integer.parseInt(imageProperty[1]),
					Integer.parseInt(imageProperty[2]),
					Integer.parseInt(imageProperty[3]),
					Integer.parseInt(imageProperty[4]),
					Integer.parseInt(imageProperty[5]));

			iu.setSrcpath(  ProjectUtil.imageUploadPath+"/"+dateString+"/"+ srcImgName);// 源图片路径名称
			iu.setSubpath(ProjectUtil.imageUploadPath + "/"+cutImgName);// 剪切图片路径名称
			smgMemberManager.updateHead(viewMember.getMemberId(),ProjectUtil.imagePrefix+"images/"+dateString + "/" + cutImgName);
			viewMember.setHeadImage(ProjectUtil.imagePrefix+"images/"+dateString + "/" + cutImgName) ;
			saveMemberInSession(request,viewMember);
			try{
				iu.cut(cutImgName.substring(cutImgName.lastIndexOf(".") + 1),dateString);
				FileUtil.deleteFile(ProjectUtil.imageUploadPath + cutImgName);
			}catch(Exception e){
				e.printStackTrace();
					return "error";
			}
		} else {
		}
	
		return "success";
	}
	@RequestMapping(value="/changePassword")
	public String changePassword(HttpServletRequest request,ModelMap model){
		setHeadTabIndex(model, 6);
		setCommunityCommonModel(request, model);
		SmgMember viewMember = getLoginMember(request);
		if ( viewMember == null){
			return toErrorPage(model, "您未登录或者登录已超时");
		}
		model.addAttribute("viewMember",viewMember);
		model.addAttribute("type","password");
			return "/member/changePassword";
		}
	
	
	@RequestMapping(value="/changePasswordAction")
	public @ResponseBody Map<String,String> changePasswordAction(HttpServletRequest request,ModelMap model){
			Map<String,String> map = new HashMap<String,String>();
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
		
			SmgMember loginMember = getLoginMember(request);
			if ( loginMember == null){
				map.put("state","-1");
				map.put("state","您未登录或者登录已超时");  
				return  map;
			}
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("oldPasswd",oldPassword);
			paramMap.put("newPasswd",newPassword);
			paramMap.put("token",(String)request.getSession().getAttribute("token"));
			Gson gson = new Gson();
			String param = gson.toJson(paramMap);
			String editMemberPasswordUrl = REG_LOGIN_SEVICE_URL+"/account/editPwd.action?param="+param;
			logger.debug(editMemberPasswordUrl);
			String editMemberPasswordResult =  HttpRequestProxy.doGet(editMemberPasswordUrl, recvEncoding);
			if ( editMemberPasswordResult == null ){
				map.put("state","-1");
				map.put("desc","修改失败,请重新登录后进行修改.");
			}else{
					smgMemberManager.updatePassword(loginMember.getMemberId(),newPassword);
					loginMember.setPassword(newPassword);
					map.put("state","1");
			}
			return  map;
			
	}
	//获取当期年月日时分秒毫秒的字符串
	public String getRoundStr() {
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(System
				.currentTimeMillis());
	}
	private String[] getHeadPath(String contextPath, String uploadPath) {
		// 外网用户上传头像存放目录
	String headPath = "/ddmap/remote/image/user/bbshead/";
	// @SuppressWarnings("unused")
	String showHeadPath = "http://img3.ddmapimg.com/user/bbshead/";
	
	// 内网测试时可放开此方法来调试
		headPath = uploadPath + "UploadUserHead/";// 内网用户上传头像存放目录
		showHeadPath = contextPath + "/UploadUserHead/";
		// showHeadPath = request.getContextPath() + "/UploadUserHead/"; 
		return new String[] { headPath, showHeadPath };
	}
	// 根据Unicode编码完美的判断中文汉字和符号
	
    private static boolean isChinese(char c) {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B

                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS

                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {

            return true;

        }

        return false;

    }

 

    // 完整的判断中文汉字和符号

    public static boolean isChinese(String strName) {

        char[] ch = strName.toCharArray();

        for (int i = 0; i < ch.length; i++) {

            char c = ch[i];

            if (isChinese(c)) {

                return true;

            }

        }

        return false;

    }
 
	
	 /** 
	 * 获取汉字串拼音首字母，英文字符不变 
	 * 
	 * @param chinese 汉字串 
	 * @return 汉语拼音首字母 
	 */ 
	public static String cn2FirstSpell(String chinese) {
			if ( StringUtil.isEmpty(chinese)){
				return "";
			}
			String firstString = chinese.substring(0,1);
			firstString = firstString.toLowerCase();
			System.out.println ( "firstString  = " +firstString );
			String englishOrNumberStr = "0123456789abcdefghijklmnopqrstuvwxyz";
			try{
				if (  englishOrNumberStr.indexOf(firstString) != -1){
					return  firstString;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			if ( !isChinese(firstString)){
				return firstString;
			}
	        StringBuffer pybf = new StringBuffer(); 
	        char[] arr = chinese.toCharArray(); 
	        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 
	        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
	        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 
	        for (int i = 0; i < arr.length; i++) { 
	                if (arr[i] > 128) { 
	                        try { 
	                                String[] _t = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat); 
	                                if (_t != null) { 
	                                        pybf.append(_t[0].charAt(0)); 
	                                } 
	                        } catch (BadHanyuPinyinOutputFormatCombination e) { 
	                                e.printStackTrace(); 
	                        } 
	                } else { 
	                        pybf.append(arr[i]); 
	                } 
	        } 
	        return pybf.toString().replaceAll("\\W", "").trim().substring(0,1); 
	} 
	@RequestMapping("/checknicknames")
	public  @ResponseBody Map<String,String> checkNickNames(
			@RequestParam(required=true) String nickNames 
			){
		Map<String,String> map = new HashMap<String,String>();
		if ( nickNames.trim().length() == 0){
			map.put("state","-1");
			map.put("desc","昵称为空");
			return map;
		}
		nickNames = nickNames.replaceAll("；",";");
		String[] nickNameArray = nickNames.split(";");
		for(String nickName:nickNameArray){
		  	 nickName = nickName.trim();
			 SmgMember member = smgMemberManager.getByNickname(nickName);
			 if ( member == null){
				 map.put("state","-1");
				 map.put("desc","查询不到昵称为 "+nickName+" 的用户");
				 return map;
			 }
		}
		map.put("state","1");
		map.put("desc","昵称正确");
		return map;
	}
	
	@RequestMapping(value="/getNicknameFirstchar")
	public void getNicknameFirstchar(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/plain");
		System.out.println(request.getParameter("nickName") );
		String a = cn2FirstSpell(request.getParameter("nickName"));
		response.getWriter().write(a);
		
	}
}

